package com.flydog.mall.controller;

import com.flydog.mall.common.api.CommonResult;
import com.flydog.mall.dto.FileUploadDto;
import com.flydog.mall.service.FileManageService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 使用Minio进行文件管理
 *
 * @author AI
 */

@RequestMapping("/minio")
@Controller
@Slf4j
@Api(tags = "minio文件管理")
public class MinioController {

    @Autowired
    private FileManageService fileManage;

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("文件上传")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "moduleName", dataType = "String", required = true, paramType = "form", value = "模块名称，文件所属的模块的名称。如品牌模块,则moduleName为\"brand\""),
            @ApiImplicitParam(name = "instanceName", dataType = "String", required = true, paramType = "form", value = "实体名称，模块下某实体的名称。如品牌foo的实体名称为\"foo\""),
            @ApiImplicitParam(name = "contentName", dataType = "String", required = true, paramType = "form", value = "文件内容名称，实体下该文件的内容名称。如品牌foo的logo文件，则内容名称为logo"),
            @ApiImplicitParam(name = "file", dataTypeClass = MultipartFile.class, required = true, paramType = "form", value = "文件内容")
    })
    public CommonResult<FileUploadDto> upload(
            @RequestParam("file") MultipartFile file,
            @RequestParam("moduleName") String moduleName,
            @RequestParam("instanceName") String instanceName,
            @RequestParam("contentName") String contentName
    ) {
        try {
            FileUploadDto dto = fileManage.upload(file, moduleName, instanceName, contentName);
            return CommonResult.success(dto);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("文件上传错误：{}", e.getMessage());
        }
        return CommonResult.failed();
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation("文件删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "objectName", dataType = "String", required = true, paramType = "form", value = "删除文件名称"),
    })
    public CommonResult<FileUploadDto> delete(@RequestParam String objectName) {
        try {
            fileManage.delete(objectName);
            return CommonResult.success(null);
        } catch (Exception e) {
            e.printStackTrace();
            log.debug(e.getMessage());
            log.info("文件{}删除错误", objectName);
        }
        return CommonResult.failed();
    }
}
